package com.example.cinemasystemv2.controller;

import com.example.cinemasystemv2.entity.User;
import com.example.cinemasystemv2.entity.Screening;
import com.example.cinemasystemv2.entity.ScreeningRoom;
import com.example.cinemasystemv2.entity.Order;
import com.example.cinemasystemv2.entity.Ticket;
import com.example.cinemasystemv2.service.UserService;
import com.example.cinemasystemv2.service.MovieService;
import com.example.cinemasystemv2.service.ScreeningService;
import com.example.cinemasystemv2.service.OrderService;
import com.example.cinemasystemv2.service.TicketService;
import com.example.cinemasystemv2.service.SystemLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.http.ResponseEntity;

import jakarta.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.Map;
import java.util.HashMap;

@Controller
@RequestMapping("/receptionist")
public class ReceptionistController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private MovieService movieService;
    
    @Autowired
    private ScreeningService screeningService;
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private TicketService ticketService;
    
    @Autowired
    private SystemLogService systemLogService;
    
    // 检查前台用户权限
    private boolean checkReceptionistRole(HttpSession session) {
        String role = (String) session.getAttribute("role");
        return "receptionist".equals(role);
    }
    
    private void addCurrentUserToModel(Model model, HttpSession session) {
        String username = (String) session.getAttribute("username");
        User currentUser = userService.getUserByUsername(username).orElse(null);
        model.addAttribute("currentUser", currentUser);
    }
    
    // 前台用户仪表板
    @GetMapping("/dashboard")
    public String dashboard(Model model, HttpSession session) {
        if (!checkReceptionistRole(session)) {
            return "redirect:/login";
        }
        
        addCurrentUserToModel(model, session);
        
        // 添加统计数据
        model.addAttribute("totalMovies", movieService.getAllMovies().size());
        model.addAttribute("todayScreenings", screeningService.getTodayScreenings().size());
        
        // 今日售票数据
        List<Order> todayOrders = orderService.getTodayOrders();
        String receptionistUsername = (String) session.getAttribute("username");
        List<Order> myTodayOrders = todayOrders.stream()
            .filter(order -> receptionistUsername.equals(order.getUsername()))
            .collect(Collectors.toList());
        
        model.addAttribute("myTodayTickets", myTodayOrders.size());
        double myTodaySales = myTodayOrders.stream()
            .filter(order -> !order.isRefunded())
            .mapToDouble(Order::getAmount)
            .sum();
        model.addAttribute("myTodaySales", myTodaySales);
        
        return "receptionist/dashboard";
    }
    
    // 影片列表页面
    @GetMapping("/movies")
    public String movieList(Model model, HttpSession session) {
        if (!checkReceptionistRole(session)) {
            return "redirect:/login";
        }
        
        addCurrentUserToModel(model, session);
        model.addAttribute("movies", movieService.getAllMovies());
        
        return "receptionist/movies";
    }
    
    // 影片搜索
    @GetMapping("/movies/search")
    public String searchMovies(@RequestParam(required = false) String title,
                              @RequestParam(required = false) String director,
                              @RequestParam(required = false) String actors,
                              Model model, HttpSession session) {
        if (!checkReceptionistRole(session)) {
            return "redirect:/login";
        }
        
        addCurrentUserToModel(model, session);
        
        List<com.example.cinemasystemv2.entity.Movie> movies;
        if ((title == null || title.trim().isEmpty()) && 
            (director == null || director.trim().isEmpty()) && 
            (actors == null || actors.trim().isEmpty())) {
            movies = movieService.getAllMovies();
        } else {
            movies = movieService.searchMoviesByMultipleFields(title, director, actors);
        }
        
        model.addAttribute("movies", movies);
        model.addAttribute("searchTitle", title);
        model.addAttribute("searchDirector", director);
        model.addAttribute("searchActors", actors);
        
        return "receptionist/movies";
    }
    
    // 场次列表页面
    @GetMapping("/screenings")
    public String screeningList(@RequestParam(defaultValue = "week") String period,
                               Model model, HttpSession session) {
        if (!checkReceptionistRole(session)) {
            return "redirect:/login";
        }
        
        addCurrentUserToModel(model, session);
        
        List<Screening> screenings;
        switch (period) {
            case "today":
                screenings = screeningService.getTodayScreenings();
                break;
            case "3days":
                screenings = screeningService.getNext3DaysScreenings();
                break;
            default:
                screenings = screeningService.getUpcomingScreenings();
        }
        
        // 为每个场次计算可用座位数
        Map<Long, Integer> availableSeatsMap = new HashMap<>();
        for (Screening screening : screenings) {
            List<Ticket> soldTickets = ticketService.getTicketsByScreeningId(screening.getId());
            int totalSeats = screening.getRoom().getTotalSeats();
            int availableSeats = totalSeats - soldTickets.size();
            availableSeatsMap.put(screening.getId(), availableSeats);
        }
        
        model.addAttribute("screenings", screenings);
        model.addAttribute("availableSeatsMap", availableSeatsMap);
        model.addAttribute("period", period);
        
        return "receptionist/screenings";
    }
    
    // 查看指定场次的座位信息
    @GetMapping("/screenings/{screeningId}/seats")
    public String viewSeats(@PathVariable Long screeningId, Model model, HttpSession session) {
        if (!checkReceptionistRole(session)) {
            return "redirect:/login";
        }
        
        addCurrentUserToModel(model, session);
        
        Optional<Screening> screeningOpt = screeningService.getScreeningById(screeningId);
        if (screeningOpt.isPresent()) {
            Screening screening = screeningOpt.get();
            model.addAttribute("screening", screening);
            
            // 获取已售座位
            List<Ticket> soldTickets = ticketService.getTicketsByScreeningId(screeningId);
            List<String> soldSeats = soldTickets.stream()
                .map(Ticket::getSeatNumber)
                .collect(Collectors.toList());
            
            model.addAttribute("soldSeats", soldSeats);
            int totalSeats = screening.getRoom().getNumRows() * screening.getRoom().getSeatsPerRow();
            model.addAttribute("totalSeats", totalSeats);
            model.addAttribute("availableSeats", totalSeats - soldSeats.size());
            
            return "receptionist/seats";
        } else {
            return "redirect:/receptionist/screenings";
        }
    }
    
    // 售票页面
    @GetMapping("/sell-ticket")
    public String sellTicketPage(Model model, HttpSession session) {
        if (!checkReceptionistRole(session)) {
            return "redirect:/login";
        }
        
        addCurrentUserToModel(model, session);
        model.addAttribute("movies", movieService.getAllMovies());
        model.addAttribute("screenings", screeningService.getUpcomingScreenings());
        
        return "receptionist/sell-ticket";
    }
    
    // 获取所有电影列表（AJAX）
    @GetMapping("/movies-list")
    @ResponseBody
    public ResponseEntity<?> getMoviesList(HttpSession session) {
        if (!checkReceptionistRole(session)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "权限不足，请重新登录");
            return ResponseEntity.ok(errorResponse);
        }
        
        return ResponseEntity.ok(movieService.getAllMovies());
    }
    
    // 获取指定电影的场次（AJAX）
    @GetMapping("/movie-screenings")
    @ResponseBody
    public ResponseEntity<Object> getMovieScreenings(@RequestParam Long movieId, HttpSession session) {
        if (!checkReceptionistRole(session)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "权限不足，请重新登录");
            return ResponseEntity.ok(errorResponse);
        }
        
        List<Screening> screenings = screeningService.getScreeningsByMovieId(movieId)
            .stream()
            .filter(screening -> screening.getStartTime().isAfter(LocalDateTime.now()))
            .collect(Collectors.toList());
        
        // 手动构建响应数据，避免懒加载问题
        List<Map<String, Object>> screeningData = screenings.stream().map(screening -> {
            Map<String, Object> data = new HashMap<>();
            data.put("id", screening.getId());
            data.put("startTime", screening.getStartTime());
            data.put("price", screening.getPrice());
            data.put("movieTitle", screening.getMovie().getTitle());
            data.put("roomName", screening.getRoom().getName());
            data.put("roomId", screening.getRoom().getId());
            return data;
        }).collect(Collectors.toList());
        
        return ResponseEntity.ok(screeningData);
    }
    
    // 获取场次座位信息（AJAX）
    @GetMapping("/screening-seats")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getScreeningSeatInfo(@RequestParam Long screeningId, HttpSession session) {
        if (!checkReceptionistRole(session)) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<Screening> screeningOpt = screeningService.getScreeningById(screeningId);
        if (screeningOpt.isPresent()) {
            Screening screening = screeningOpt.get();
            List<Ticket> soldTickets = ticketService.getTicketsByScreeningId(screeningId);
            List<String> occupiedSeats = soldTickets.stream()
                .map(Ticket::getSeatNumber)
                .collect(Collectors.toList());
            
            // 手动构建Screening数据，避免懒加载问题
            Map<String, Object> screeningMap = new HashMap<>();
            screeningMap.put("id", screening.getId());
            screeningMap.put("startTime", screening.getStartTime());
            screeningMap.put("price", screening.getPrice());
            
            // 添加Movie信息
            Map<String, Object> movieMap = new HashMap<>();
            movieMap.put("id", screening.getMovie().getId());
            movieMap.put("title", screening.getMovie().getTitle());
            screeningMap.put("movie", movieMap);
            
            // 添加Room信息
            Map<String, Object> roomMap = new HashMap<>();
            roomMap.put("id", screening.getRoom().getId());
            roomMap.put("name", screening.getRoom().getName());
            roomMap.put("numRows", screening.getRoom().getNumRows());
            roomMap.put("seatsPerRow", screening.getRoom().getSeatsPerRow());
            roomMap.put("totalSeats", screening.getRoom().getTotalSeats());
            screeningMap.put("room", roomMap);
            
            Map<String, Object> result = new HashMap<>();
            result.put("screening", screeningMap);
            result.put("totalSeats", screening.getRoom().getTotalSeats());
            result.put("occupiedSeats", occupiedSeats);
            
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    // 获取场次座位信息（AJAX）- 用于座位图显示
    @GetMapping("/api/screenings/{screeningId}/seats")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getScreeningSeatsForMap(@PathVariable Long screeningId, HttpSession session) {
        if (!checkReceptionistRole(session)) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<Screening> screeningOpt = screeningService.getScreeningById(screeningId);
        if (screeningOpt.isPresent()) {
            Screening screening = screeningOpt.get();
            ScreeningRoom room = screening.getRoom();
            
            // 获取已售座位
            List<Ticket> soldTickets = ticketService.getTicketsByScreeningId(screeningId);
            List<String> occupiedSeats = soldTickets.stream()
                .map(Ticket::getSeatNumber)
                .collect(Collectors.toList());
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("rows", room.getNumRows());
            result.put("seatsPerRow", room.getSeatsPerRow());
            result.put("occupiedSeats", occupiedSeats);
            result.put("totalSeats", room.getTotalSeats());
            
            return ResponseEntity.ok(result);
        } else {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "场次不存在");
            return ResponseEntity.ok(result);
        }
    }
    
    // 处理售票（AJAX）
    @PostMapping("/sell-ticket")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> processSellTicket(@RequestParam Long screeningId,
                                   @RequestParam String seatNumbers,
                                   @RequestParam(defaultValue = "false") boolean isChildTicket,
                                   @RequestParam(defaultValue = "1.0") double discount,
                                   HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        if (!checkReceptionistRole(session)) {
            response.put("success", false);
            response.put("message", "权限不足");
            return ResponseEntity.ok(response);
        }
        
        try {
            Optional<Screening> screeningOpt = screeningService.getScreeningById(screeningId);
            if (!screeningOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "场次不存在");
                return ResponseEntity.ok(response);
            }
            
            Screening screening = screeningOpt.get();
            
            // 检查场次是否已开始
            if (screening.getStartTime().isBefore(LocalDateTime.now())) {
                response.put("success", false);
                response.put("message", "该场次已开始，无法售票");
                return ResponseEntity.ok(response);
            }
            
            // 解析座位号
            List<String> seats = Arrays.asList(seatNumbers.split(","))
                .stream()
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.toList());
            
            if (seats.isEmpty()) {
                response.put("success", false);
                response.put("message", "请选择座位");
                return ResponseEntity.ok(response);
            }
            
            // 检查座位是否已被占用
            List<Ticket> existingTickets = ticketService.getTicketsByScreeningId(screeningId);
            List<String> soldSeats = existingTickets.stream()
                .map(Ticket::getSeatNumber)
                .collect(Collectors.toList());
            
            for (String seat : seats) {
                if (soldSeats.contains(seat)) {
                    response.put("success", false);
                    response.put("message", "座位 " + seat + " 已被占用");
                    return ResponseEntity.ok(response);
                }
            }
            
            // 计算票价
            double basePrice = screening.getPrice();
            if (isChildTicket) {
                basePrice *= 0.8; // 儿童票8折
            }
            basePrice *= discount; // 应用折扣
            
            double totalAmount = basePrice * seats.size();
            
            // 创建订单
            Order order = new Order();
            order.setOrderId("ORD" + System.currentTimeMillis() + (int)(Math.random() * 1000)); // 手动设置订单ID
            order.setScreening(screening);
            order.setAmount(totalAmount);
            order.setTicketCount(seats.size());
            order.setUsername((String) session.getAttribute("username"));
            order.setOrderTime(LocalDateTime.now());
            order.setRefunded(false);
            
            Order savedOrder = orderService.saveOrder(order);
            
            // 创建电影票
            for (String seat : seats) {
                Ticket ticket = new Ticket();
                ticket.setOrderId(savedOrder.getOrderId());
                ticket.setScreeningId(screeningId);
                ticket.setSeatNumber(seat);
                ticket.setTicketNumber(UUID.randomUUID().toString().replace("-", "").substring(0, 12).toUpperCase());
                ticket.setPrice(basePrice);
                ticket.setIsChildTicket(isChildTicket);
                ticket.setCreatedAt(LocalDateTime.now());
                
                ticketService.saveTicket(ticket);
            }
            
            // 记录日志
            String receptionistUsername = (String) session.getAttribute("username");
            systemLogService.log("售票: 场次" + screeningId + ", 座位" + seatNumbers + ", 金额" + totalAmount, 
                               receptionistUsername, "SELL_TICKET");
            
            // 获取所有创建的电子票号
            List<Ticket> tickets = ticketService.getTicketsByOrderId(savedOrder.getOrderId());
            List<String> ticketNumbers = tickets.stream()
                .map(Ticket::getTicketNumber)
                .collect(Collectors.toList());
            
            // 返回成功响应
            response.put("success", true);
            response.put("message", "售票成功");
            
            Map<String, Object> orderData = new HashMap<>();
            orderData.put("orderId", savedOrder.getOrderId());
            orderData.put("totalAmount", totalAmount);
            orderData.put("ticketCount", seats.size());
            orderData.put("ticketNumbers", ticketNumbers);
            orderData.put("seats", seats);
            response.put("order", orderData);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "售票失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    // 退票页面
    @GetMapping("/refund-ticket")
    public String refundTicketPage(Model model, HttpSession session) {
        if (!checkReceptionistRole(session)) {
            return "redirect:/login";
        }
        
        addCurrentUserToModel(model, session);
        
        return "receptionist/refund-ticket";
    }
    
    // 查询电子票信息（AJAX）
    @GetMapping("/ticket-info")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getTicketInfo(@RequestParam String ticketNumber, HttpSession session) {
        if (!checkReceptionistRole(session)) {
            return ResponseEntity.status(401).build();
        }
        
        Map<String, Object> response = new HashMap<>();
        
        // 首先尝试作为电子票号查询
        Optional<Ticket> ticketOpt = ticketService.getTicketByTicketNumber(ticketNumber);
        
        // 如果没找到，并且输入的是以ORD开头的字符串，则尝试作为订单号查询
        if (!ticketOpt.isPresent() && ticketNumber.startsWith("ORD")) {
            List<Ticket> tickets = ticketService.getTicketsByOrderId(ticketNumber);
            if (!tickets.isEmpty()) {
                // 使用订单中的第一张票
                ticketOpt = Optional.of(tickets.get(0));
            }
        }
        
        if (ticketOpt.isPresent()) {
            Ticket ticket = ticketOpt.get();
            Optional<Order> orderOpt = orderService.getOrderByOrderId(ticket.getOrderId());
            Optional<Screening> screeningOpt = screeningService.getScreeningById(ticket.getScreeningId());
            
            if (orderOpt.isPresent() && screeningOpt.isPresent()) {
                Order order = orderOpt.get();
                Screening screening = screeningOpt.get();
                
                Map<String, Object> ticketInfo = new HashMap<>();
                ticketInfo.put("ticketNumber", ticket.getTicketNumber());
                ticketInfo.put("movieTitle", screening.getMovie().getTitle());
                ticketInfo.put("roomName", screening.getRoom().getName());
                ticketInfo.put("screeningTime", screening.getStartTime());
                ticketInfo.put("seatNumbers", ticket.getSeatNumber());
                ticketInfo.put("ticketType", ticket.getIsChildTicket() ? "child" : "adult");
                ticketInfo.put("unitPrice", ticket.getPrice());
                ticketInfo.put("ticketCount", order.getTicketCount());
                ticketInfo.put("totalAmount", order.getAmount());
                ticketInfo.put("purchaseTime", order.getOrderTime());
                ticketInfo.put("status", order.isRefunded() ? "REFUNDED" : "VALID");
                
                response.put("success", true);
                response.put("ticket", ticketInfo);
                
                return ResponseEntity.ok(response);
            }
        }
        
        response.put("success", false);
        return ResponseEntity.ok(response);
    }
    
    // 处理退票
    @PostMapping("/refund-ticket")
    public String processRefundTicket(@RequestParam String ticketNumber,
                                     HttpSession session,
                                     RedirectAttributes redirectAttributes) {
        if (!checkReceptionistRole(session)) {
            return "redirect:/login";
        }
        
        try {
            Optional<Ticket> ticketOpt = ticketService.getTicketByTicketNumber(ticketNumber);
            if (!ticketOpt.isPresent()) {
                redirectAttributes.addFlashAttribute("error", "电子票号不存在");
                return "redirect:/receptionist/refund-ticket";
            }
            
            Ticket ticket = ticketOpt.get();
            Optional<Order> orderOpt = orderService.getOrderByOrderId(ticket.getOrderId());
            Optional<Screening> screeningOpt = screeningService.getScreeningById(ticket.getScreeningId());
            
            if (!orderOpt.isPresent() || !screeningOpt.isPresent()) {
                redirectAttributes.addFlashAttribute("error", "订单或场次信息不存在");
                return "redirect:/receptionist/refund-ticket";
            }
            
            Order order = orderOpt.get();
            Screening screening = screeningOpt.get();
            
            // 检查是否已退票
            if (order.isRefunded()) {
                redirectAttributes.addFlashAttribute("error", "该票已退票");
                return "redirect:/receptionist/refund-ticket";
            }
            
            // 检查是否可以退票（开映前1小时）
            if (screening.getStartTime().isBefore(LocalDateTime.now().plusHours(1))) {
                redirectAttributes.addFlashAttribute("error", "开映前1小时内不允许退票");
                return "redirect:/receptionist/refund-ticket";
            }
            
            // 计算退票金额（可以根据策略调整）
            double refundAmount = ticket.getPrice();
            
            // 标记订单为已退票
            order.setRefunded(true);
            order.setRefundTime(LocalDateTime.now());
            order.setRefundAmount(refundAmount);
            orderService.saveOrder(order);
            
            // 删除票据（释放座位）
            ticketService.deleteTicket(ticket.getId());
            
            // 记录日志
            String receptionistUsername = (String) session.getAttribute("username");
            systemLogService.log("退票: 电子票号" + ticketNumber + ", 退款金额" + refundAmount, 
                               receptionistUsername, "REFUND_TICKET");
            
            redirectAttributes.addFlashAttribute("success", "退票成功！退款金额: " + refundAmount + "元");
            
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "退票失败: " + e.getMessage());
        }
        
        return "redirect:/receptionist/refund-ticket";
    }
    
    // 处理前端AJAX退票请求
    @PostMapping("/process-refund")
    @ResponseBody
    public Map<String, Object> processRefund(@RequestBody Map<String, String> requestData,
                                           HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        if (!checkReceptionistRole(session)) {
            response.put("success", false);
            response.put("message", "权限不足");
            return response;
        }
        
        String ticketNumber = requestData.get("ticketNumber");
        
        try {
            Optional<Ticket> ticketOpt = ticketService.getTicketByTicketNumber(ticketNumber);
            if (!ticketOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "电子票号不存在");
                return response;
            }
            
            Ticket ticket = ticketOpt.get();
            Optional<Order> orderOpt = orderService.getOrderByOrderId(ticket.getOrderId());
            Optional<Screening> screeningOpt = screeningService.getScreeningById(ticket.getScreeningId());
            
            if (!orderOpt.isPresent() || !screeningOpt.isPresent()) {
                response.put("success", false);
                response.put("message", "订单或场次信息不存在");
                return response;
            }
            
            Order order = orderOpt.get();
            Screening screening = screeningOpt.get();
            
            // 检查是否已退票
            if (order.isRefunded()) {
                response.put("success", false);
                response.put("message", "该票已退票");
                return response;
            }
            
            // 检查是否可以退票（开映前1小时）
            if (screening.getStartTime().isBefore(LocalDateTime.now().plusHours(1))) {
                response.put("success", false);
                response.put("message", "开映前1小时内不允许退票");
                return response;
            }
            
            // 计算退票金额（可以根据策略调整）
            double refundAmount = ticket.getPrice();
            
            // 标记订单为已退票
            order.setRefunded(true);
            order.setRefundTime(LocalDateTime.now());
            order.setRefundAmount(refundAmount);
            orderService.saveOrder(order);
            
            // 删除票据（释放座位）
            ticketService.deleteTicket(ticket.getId());
            
            // 记录日志
            String receptionistUsername = (String) session.getAttribute("username");
            systemLogService.log("退票: 电子票号" + ticketNumber + ", 退款金额" + refundAmount, 
                               receptionistUsername, "REFUND_TICKET");
            
            response.put("success", true);
            response.put("refundAmount", refundAmount);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "退票失败: " + e.getMessage());
        }
        
        return response;
    }
    
    // 查看订单详情
    @GetMapping("/order/{orderId}")
    public String viewOrder(@PathVariable String orderId, Model model, HttpSession session) {
        if (!checkReceptionistRole(session)) {
            return "redirect:/login";
        }
        
        addCurrentUserToModel(model, session);
        
        Optional<Order> orderOpt = orderService.getOrderByOrderId(orderId);
        if (orderOpt.isPresent()) {
            Order order = orderOpt.get();
            List<Ticket> tickets = ticketService.getTicketsByOrderId(orderId);
            
            model.addAttribute("order", order);
            model.addAttribute("tickets", tickets);
            
            if (!tickets.isEmpty()) {
                Optional<Screening> screeningOpt = screeningService.getScreeningById(tickets.get(0).getScreeningId());
                screeningOpt.ifPresent(screening -> {
                    model.addAttribute("screening", screening);
                    model.addAttribute("movie", screening.getMovie());
                });
            }
            
            return "receptionist/order-detail";
        } else {
            return "redirect:/receptionist/dashboard";
        }
    }
    
    // 显示所有已售出的票的信息
    @GetMapping("/sold-tickets")
    public String viewSoldTickets(@RequestParam(defaultValue = "all") String period, Model model, HttpSession session) {
        if (!checkReceptionistRole(session)) {
            return "redirect:/login";
        }
        
        addCurrentUserToModel(model, session);
        
        List<Ticket> tickets;
        String periodName;
        
        switch (period) {
            case "today":
                tickets = ticketService.getTodayTickets();
                periodName = "今日";
                break;
            case "week":
                tickets = ticketService.getThisWeekTickets();
                periodName = "本周";
                break;
            case "month":
                tickets = ticketService.getThisMonthTickets();
                periodName = "本月";
                break;
            default:
                tickets = ticketService.getAllTickets();
                periodName = "全部";
        }
        
        // 获取票的详细信息
        List<Map<String, Object>> ticketDetails = tickets.stream().map(ticket -> {
            Map<String, Object> detail = new HashMap<>();
            detail.put("ticket", ticket);
            
            // 获取场次信息
            Optional<Screening> screeningOpt = screeningService.getScreeningById(ticket.getScreeningId());
            screeningOpt.ifPresent(screening -> {
                detail.put("screening", screening);
                detail.put("movie", screening.getMovie());
                detail.put("room", screening.getRoom());
            });
            
            // 获取订单信息
            Optional<Order> orderOpt = orderService.getOrderByOrderId(ticket.getOrderId());
            orderOpt.ifPresent(order -> detail.put("order", order));
            
            return detail;
        }).collect(Collectors.toList());
        
        model.addAttribute("ticketDetails", ticketDetails);
        model.addAttribute("period", period);
        model.addAttribute("periodName", periodName);
        model.addAttribute("totalTickets", tickets.size());
        
        // 计算总销售额
        double totalSales = tickets.stream().mapToDouble(Ticket::getPrice).sum();
        model.addAttribute("totalSales", totalSales);
        
        return "receptionist/sold-tickets";
    }
}